<template>
  <div class="main-content">
    <div class="row">
      <div class="col-sm-4 col-md-3">
        <ul class="template-title-fl">
          <li><button type="button" class="btn btn-default btn-theme addBtn" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0001) >= 0" v-on:click="openSelfDeptModal('A')">新增</button></li>
          <li><button type="button" class="btn btn-default btn-theme" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0002) >= 0" v-on:click="openSelfDeptModal('U')">修改</button></li>
          <li><button type="button" class="btn btn-default btn-theme" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0003) >= 0" v-on:click="delDept">删除</button></li>
          <li><button type="button" class="btn btn-default btn-theme" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0004) >= 0" v-on:click="openEditDeptModal('M')">合并</button></li>
          <li><button type="button" class="btn btn-default btn-theme" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0005) >= 0" v-on:click="openEditDeptModal('C')">转移</button></li>
        </ul>
        <div class="table-filter" style="overflow-y: auto;height: 450px;">
          <ul class="template-title-fls" style="padding: 10px 0 0 10px;">
            <li><button type="button" class="btn btn-default btn-theme" v-on:click="queryDetpByDeptName()">查询</button></li>
            <li><input type="text" v-model="searchDeptModel.deptName" id="key" class="form-control-sm" style="width:100%;" placeholder="请输入机构名称" /></li>

          </ul>
          <ul id="orgTree" class="ztree"></ul>
          <span id="orgTreeText" style="padding-left: 10px;font-weight: bolder;display: none;">无查询结果</span>
        </div>
      </div>
      <div class="col-sm-8 col-md-9">
        <form id="searchForm">
          <ul class="template-title-fls">
            <li><input type="text" v-model="searchUserModel.accountName" name="accountName" class="form-control-sm" placeholder="姓名" /></li>
            <li><input type="text" v-model="searchUserModel.phone" class="form-control-sm" placeholder="手机号码" /></li>
            <li>
              <select class="form-control-sm" style="float:left" v-model="searchUserModel.accountType">
                <option value="">是否为超管</option>
                <option value="0">是</option>
                <option value="1">否</option>
              </select>
            </li>
            <li><button type="button" class="btn btn-default btn-theme addBtn2" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0006) >= 0" v-on:click="openSelfUserModal('A', '')">新增</button></li>
            <li><button type="button" class="btn btn-default btn-theme" v-on:click="loadPartnerByDept()">查询</button></li>
          </ul>
        </form>
        <div class="table-responsive">
          <table class="table table-striped table-bordered min-width-790">
            <thead>
              <tr>
                <th width="7%">序号</th>
                <th width="10%">部门</th>
                <th width="15%">员工姓名</th>
                <th width="15%">联系电话</th>
                <th width="10%">角色</th>
                <th width="5%">状态</th>
                <th width="15%">驻守案场</th>
                <th width="28%">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in rows">
                <td>{{index + 1}}</td>
                <td>{{row.dempName}}</td>
                <td>{{row.accountName}}</td>
                <td>{{row.phone}}</td>
                <td v-if="row.accountType == 0" style="color: red;">超级管理员</td>
                <td v-else>{{ row.roleName }}</td>
                <td><span :class="[{stateOne: row.status==1, stateTwo: row.status==0}]">{{row.status==1?"启用":"禁用"}}</span></td>
                <td :title="row.propertyIdsCN">{{row.propertyIdsCN | substrFilter(0, 20)}}</td>
                <td>
                  <button type="button" class="btnA edit" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0007) >= 0" @click="openSelfUserModal('U', row.id)">编辑</button>
                  <button type="button" class="btnA delete-btn" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0008) >= 0" @click="delPartner(row.id)">删除</button>
                  <button type="button" class="btnA delete-btn" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0009) >= 0" @click="forbiddenOrNotPartner(row.id, row.status)">{{row.status==1?"禁用":"启用"}}</button>
                  <button type="button" class="btnA delete-btn" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0010) >= 0" @click="openChangePartnerDept(row.id,row.accountName)">调整部门</button>
                  <button type="button" class="btnA initial" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0011) >= 0" @click="openBindPremisesModal(row.id, row.accountName)">楼盘权限</button>
                  <button type="button" class="btnA initial" v-show="userAuthResources.indexOf(resourcesList.menu_0003_0001_0011) >= 0" @click="openBindDeptPermissionModal(row.id, row.accountName)">机构权限</button>
                  <button type="button" class="btnA initial" v-on:click="openMessageSettingModal(row.id, row.accountName)">消息配置</button>
                  <button type="button" class="btnA delete-btn" v-on:click="openSelfUserModal('V', row.id);">查看</button>
                  <!-- <button 
										v-if="row.accountType == 0"
										type="button" 
										class="btnA delete-btn" 
										v-on:click="chooseUserClick" >变更管理员</button> -->
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div id="laypage_self_dept"></div>
      </div>
    </div>
    <selfDeptModal v-bind:selfDeptInfo="selfDeptInfo" v-on:selfDeptListener='selfDeptReturn'></selfDeptModal>
    <selfUserModal v-bind:selfUserInfo="selfUserInfo" v-on:selfUserListener='selfUserReturn'></selfUserModal>
    <!-- <bindPremisesModal v-bind:bindPremisesInfo="bindPremisesInfo" v-on:bindPremisesListener='bindPremisesReturn'></bindPremisesModal> -->
    <mergeDeptModal v-bind:mergeDeptModal="acceptDept" v-on:saveOrgListener='selfDeptReturn' ref="mergeD"></mergeDeptModal>
    <changeDeptModal v-bind:mergeDeptModal="acceptDept" v-on:saveOrgListener='selfDeptReturn' ref="changeD"></changeDeptModal>
    <userChangeDeptModal v-bind:partnerModal="partnerInfo" v-on:selfUserListener='selfUserReturn'></userChangeDeptModal>
    <el-dialog title="选择人员" ref="chooseDialog" width="940px" :visible.sync="chooseUserVisible" :before-close="chooseUserModalClose">
      <selfDeptUser ref="selfDeptUser" v-if="chooseUserVisible" :user-list="tableData"></selfDeptUser>
      <span slot="footer" class="dialog-footer">
        <button class="btn screen-submit" style="position: static" @click="getSaveData">确认选择</button>
      </span>
    </el-dialog>
    <premisesListModal :bindPremisesInfo='bindPremisesInfo' v-on:closeModal='closeModal'></premisesListModal>
    <messageSettingModal :bindPremisesInfo='bindPremisesInfo' :messageModalShow='messageModalShow' v-on:closeMessageModal='closeMessageModal'></messageSettingModal>
    <selfDeptPermissionModal :bindPartnerInfo='bindPartnerInfo'></selfDeptPermissionModal>
  </div>
</template>

<script>
import selfDeptUser from "./components/selfDeptUser.vue";
import selfDeptModal from "./selfDeptModal.vue";
import selfUserModal from "./selfUserModal.vue";
// import bindPremisesModal from './bindPremisesModal.vue'
import ztreeCore from "../../assets/js/zTree/jquery.ztree.core-3.5.min.js";
import ztreeAll from "../../assets/js/zTree/jquery.ztree.all.min.js";
import ztreeHide from "../../assets/js/zTree/jquery.ztree.exhide.js";
import mergeDeptModal from "./mergeDept.vue";
import changeDeptModal from "./changeDept.vue";
import userChangeDeptModal from "./userChangeDept.vue";
import { API, Log, Utils, Service } from "../../js/base";
import premisesListModal from "./components/PremisesListModal.vue";
import messageSettingModal from "./components/MessageSettingModal.vue";
import selfDeptPermissionModal from "./selfDeptPermissionModal.vue";

export default {
  data() {
    return {
      messageModalShow: false,
      selectPremises: [],
      loginInfo: {
        userId: window.localStorage.getItem("1_userId"),
        isLogin: window.localStorage.getItem("1_isLogin"),
        accountType: window.localStorage.getItem("1_accountType"),
      },
      orgTreeData: [],
      rows: [],
      pageInfo: {
        pageNo: 1,
        pageSize: 10,
      },
      addUserShow: false,
      addOrgShow: false,
      searchUserModel: {
        accountName: "",
        phone: "",
        accountType: "",
      },
      selfDeptInfo: {
        orgId: "",
        optType: "",
      },
      selfUserInfo: {
        partnerId: "",
        orgId: "",
        optType: "",
      },
      forbiddenOrNotInfo: {
        id: "",
        status: "",
      },
      bindPremisesInfo: {
        partnerId: "",
        partnerName: "",
      },
      bindPartnerInfo: {
        partnerId: "",
        partnerName: "",
      },
      acceptDept: {
        id: "",
        level: "",
        name: "",
      },
      partnerInfo: {
        id: "",
        name: "",
      },
      searchDeptModel: {
        deptName: "",
      },
      hiddenNodes: [],
      nodeList: [],
      resourcesList: {
        menu_0003_0001_0001: "menu_0003_0001_0001", //本部机构新增
        menu_0003_0001_0002: "menu_0003_0001_0002", //本部机构编辑
        menu_0003_0001_0003: "menu_0003_0001_0003", //本部机构删除
        menu_0003_0001_0004: "menu_0003_0001_0004", //本部机构合并
        menu_0003_0001_0005: "menu_0003_0001_0005", //本部机构转移
        menu_0003_0001_0006: "menu_0003_0001_0006", //本部人员新增
        menu_0003_0001_0007: "menu_0003_0001_0007", //本部人员编辑
        menu_0003_0001_0008: "menu_0003_0001_0008", //本部人员删除
        menu_0003_0001_0009: "menu_0003_0001_0009", //本部人员启用/禁用
        menu_0003_0001_0010: "menu_0003_0001_0010", //本部人员调整部门
        menu_0003_0001_0011: "menu_0003_0001_0011", //本部人员驻守案场
      },
      userAuthResources: window.localStorage.getItem("userAuthResources"),
      chooseUserVisible: false,
      tableData: [],
      getReferrerLoading: false,
    };
  },
  components: {
    selfDeptUser,
    selfDeptModal,
    selfUserModal,
    // bindPremisesModal,
    mergeDeptModal,
    changeDeptModal,
    userChangeDeptModal,
    premisesListModal,
    messageSettingModal,
    selfDeptPermissionModal,
  },
  mounted: function() {
    this.loadOrgTreeData();
  },
  methods: {
    closeModal() {
      this.bindPremisesInfo.partnerId = "";
    },
    closeMessageModal() {
      this.messageModalShow = false;
    },
    getRecommendList(id) {
      const _this = this;
      _this.getReferrerLoading = true;
      _this.recommendList = [];
      if (!id) return;
      let index = -1;
      Service.Recommend.getRecommendList(id, this)
        .then((list) => {
          _this.getReferrerLoading = false;
          if (list && list.length) {
            list.forEach((item) => {
              item.dempName = item.deptName;
              item.accountName = item.userName;
              index = _this.recommendList.findIndex(
                (i) => i.recommenderUuid === item.recommenderUuid
              );
              if (index < 0) {
                // 未找到
                _this.recommendList.push(item);
              }
            });
            //_this.recommendList = list
          }
        })
        .catch((e) => {
          _this.getReferrerLoading = false;
        });
    },
    /**
     * 变更管理人按钮
     */
    chooseUserClick() {
      this.chooseUserVisible = true;
      this.getRecommendList(1070);
    },
    chooseUserModalClose() {
      this.$refs.chooseDialog.$children[0].resetUserItem();
      this.chooseUserVisible = false;
    },
    cancelReferrer(row) {
      this.tableData = this.tableData.filter((item) => {
        return item.recommenderId !== row.recommenderId;
      });
    },
    batchCancel() {
      if (!this.multipleSelection.length) {
        Utils.showWarnMsg("请选择推荐人");
      } else {
        this.multipleSelection.forEach((row) => {
          this.tableData = this.tableData.filter((item) => {
            return item.recommenderId !== row.recommenderId;
          });
        });
      }
    },
    getSaveData() {
      const _this = this;
      let tableData = JSON.parse(JSON.stringify(_this.tableData));
      this.chooseUserVisible = false;
      const userItemList = this.$refs.selfDeptUser.$refs.userItem;

      let userInfoList = [];
      if (userItemList && userItemList.length) {
        userItemList.forEach((item) => {
          if (item.selected && item.userInfo) {
            // item为vue实例，select是组件实例属性，标记是否选中
            item.userInfo.recommenderId = item.userInfo.id;
            item.userInfo.selected = item.selected;
            userInfoList.push(item.userInfo);
          } else if (!item.selected) {
            // 原有选中，但有此次取消的
            let index = tableData.findIndex(
              (i) => i.recommenderId === item.userInfo.id
            );
            if (index > -1) {
              tableData.splice(index, 1);
            }
          }
        });
        let tempList = [];
        if (tableData.length) {
          // 有值去重
          tableData = [...tableData, ...userInfoList];
          let obj = {},
            tempKey = "";
          tableData.forEach((item) => {
            tempKey = "key-" + item.recommenderId;
            if (!obj[tempKey]) {
              tempList.push(item);
              obj[tempKey] = true; // 标记该值已存在
            }
          });
        } else {
          tempList = userInfoList;
        }

        /* 调试数据，待删除*/
        let str1 = "原有推荐人: ",
          str2 = "修改后推荐人: ";
        this.tableData.forEach((item, index) => {
          str1 += item.accountName + "、";
        });
        tempList.forEach((item, index) => {
          str2 += item.accountName + "、";
        });
        /* 调试数据，待删除end */

        this.tableData = [...tempList];
      }
    },
    loadOrgTreeData: function() {
      var _self = this;
      //ztree基础属性设置
      var setting = {
        data: {
          simpleData: {
            enable: true,
          },
        },
        callback: {
          onClick: _self.zreeOnClick,
        },
      };
      var body = {};
      body.params = {};
      var url = _self.utilHelper.apiUrl + "/api/getDeptTree";
      _self.$http.post(url, body).then(
        (response) => {
          var resData = response.body.resData;
          var nodesList = resData.nodesList;
          var result = resData.result;
          $.fn.zTree.init($("#orgTree"), setting, nodesList);
          _self.searchDeptModel.deptName = "";
          //机构树加载成功后,加载经纪人数据
          _self.loadPartnerByDept();
        },
        (response) => {}
      );
    },
    zreeOnClick: function(event, treeId, treeNode) {
      this.loadPartnerByDept();
    },
    openSelfDeptModal(optType) {
      //获取选中的树节点
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if (allNodes.length > 0 && nodes.length > 0) {
        //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
        var selNode = nodes[0];
        //将节点信息及操作按钮的点击事件类型向下传递给子组件
        this.selfDeptInfo.orgId = selNode.id;
        this.selfDeptInfo.optType = optType;
        $("#selfDeptModal").modal("show");
      } else {
        if (allNodes.length == 0 && optType == "A") {
          this.selfDeptInfo.orgId = 0;
          this.selfDeptInfo.optType = optType;
          $("#selfDeptModal").modal("show");
        } else {
          //未选中任何部门，提示用户选择
          layer.msg("请选择一个部门 ", {
            time: 1000,
          });
        }
      }
    },
    selfDeptReturn() {
      this.loadOrgTreeData();
    },
    delDept: function() {
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length > 0) {
        //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
        var selNode = nodes[0];
        var id = selNode.id;
        var params = {};
        params["id"] = id;
        layer.confirm(
          "您是否要删除该机构？",
          {
            btn: ["确定删除", "再考虑考虑"], //按钮
          },
          function() {
            var body = {};
            body.params = params;
            var url = _self.utilHelper.apiUrl + "/api/delDept";
            _self.$http.post(url, body).then(
              (response) => {
                var resData = response.body.resData;
                var result = resData.result;
                var resultMsg = resData.resultMsg;
                //输出操作信息
                layer.msg(
                  resultMsg,
                  {
                    time: 1000,
                  },
                  function() {
                    if ("1" == result) {
                      _self.loadOrgTreeData();
                    }
                  }
                );
              },
              (response) => {}
            );
          },
          function() {}
        );
      } else {
        //未选中任何部门，提示用户选择
        layer.msg("请选择一个要删除的部门", {
          time: 1000,
        });
      }
    },
    loadPartnerByDept: function(obj) {
      //根据机构信息，获取用户
      var _self = this;
      var params = {};
      if (!obj) {
        _self.pageInfo.pageNo = 1;
        _self.pageInfo.pageSize = 10;
      }
      params["pageNo"] = _self.pageInfo.pageNo;
      params["pageSize"] = _self.pageInfo.pageSize;
      params["accountName"] = _self.searchUserModel.accountName;
      params["phone"] = _self.searchUserModel.phone;
      params["accountType"] = _self.searchUserModel.accountType;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      if (treeObj) {
        var node = treeObj.getSelectedNodes();
        if (node.length > 0) {
          var childNodes = treeObj.transformToArray(node);
          var nodes = "";
          for (var i = 0; i < childNodes.length; i++) {
            nodes += parseInt(childNodes[i].id) + ",";
          }
          params["deptIds"] = nodes.substring(0, nodes.lastIndexOf(","));
          //获取机构门店组别
          // _self.getQRCodeInfoByNode(node[0]);
        } else {
        }
      }
      var body = {};
      body.params = params;
      var url = this.utilHelper.apiUrl + "/api/getDevPartnerPage";
      this.$http.post(url, body).then(
        (response) => {
          var resData = response.body.resData;
          var total = resData.page.total;
          var totalPages = resData.page.totalPages;
          var current = resData.page.pageNumber;
          var rows = resData.page.rows;
          _self.rows = rows;
          //加载分页组件
          if (totalPages >= 0) {
            layui.laypage.render({
              elem: $("#laypage_self_dept"), //容器。值支持id名、原生dom对象，jquery对象,
              limit: _self.pageInfo.pageSize,
              curr: current,
              count: total,
              theme: "#f87242;", //皮肤
              first: "首页", //若不显示，设置false即可
              last: "尾页", //若不显示，设置false即可
              prev: "上一页", //若不显示，设置false即可
              next: "下一页", //若不显示，设置false即可
              layout: ["prev", "page", "next", "skip", "count"],
              jump: function(obj, first) {
                if (!first) {
                  _self.pageInfo.pageNo = obj.curr;
                  _self.loadPartnerByDept(true);
                }
              },
            });
          }
        },
        (response) => {
          console.log("加载会员失败");
        }
      );
    },
    openSelfUserModal(optType, partnerId) {
      //获取选中的树节点
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if ("A" == optType) {
        //新增需要机构节点
        if (nodes.length > 0) {
          //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
          var selNode = nodes[0];
          this.selfUserInfo.orgId = selNode.id;
          this.selfUserInfo.optType = optType;
          $("#selfUserModal").modal("show");
        } else {
          //未选中任何部门，提示用户选择
          layer.msg("请选择一个部门 ", {
            time: 1000,
          });
        }
      } else if ("U" == optType || "V" == optType) {
        //修改无需机构节点，需得到会员ID
        this.selfUserInfo.partnerId = partnerId;
        this.selfUserInfo.optType = optType;
        $("#selfUserModal").modal("show");
      }
    },
    selfUserReturn() {
      this.loadPartnerByDept(true);
    },
    forbiddenOrNotPartner(partnerId, status) {
      //0: 禁用 1: 启用
      //禁用变启用,启用变禁用
      var _self = this;
      var operationMsg = "禁用";
      if (status == 0) {
        operationMsg = "启用";
      }
      layer.confirm(
        "您是否要" + operationMsg + "该人员？",
        {
          btn: ["确定" + operationMsg, "再考虑考虑"], //按钮
        },
        function() {
          _self.forbiddenOrNotInfo.id = partnerId;
          _self.forbiddenOrNotInfo.status = status;
          var params = _self.forbiddenOrNotInfo;
          var body = {};
          body.params = params;
          var url = _self.utilHelper.apiUrl + "/api/forbiddenOrNotPartner";
          _self.$http.post(url, body).then(
            (response) => {
              var resData = response.body.resData;
              var result = resData.result;
              var resultMsg = resData.resultMsg;
              //输出操作信息
              layer.msg(
                resultMsg,
                {
                  time: 1000,
                },
                function() {
                  if ("1" == result) {
                    _self.loadPartnerByDept(true);
                  }
                }
              );
            },
            (response) => {}
          );
        },
        function() {}
      );
    },
    delPartner(partnerId) {
      //0: 禁用 1: 启用
      //禁用变启用,启用变禁用
      var _self = this;
      layer.confirm(
        "您是否要删除该人员？",
        {
          btn: ["确定删除", "再考虑考虑"], //按钮
        },
        function() {
          var params = { id: partnerId };
          var body = {};
          body.params = params;
          var url = _self.utilHelper.apiUrl + "/api/delPartner";
          _self.$http.post(url, body).then(
            (response) => {
              var resData = response.body.resData;
              var result = resData.result;
              var resultMsg = resData.resultMsg;
              //输出操作信息
              layer.msg(
                resultMsg,
                {
                  time: 1000,
                },
                function() {
                  if ("1" == result) {
                    _self.loadPartnerByDept(true);
                  }
                }
              );
            },
            (response) => {}
          );
        },
        function() {}
      );
    },
    openBindPremisesModal(partnerId, partnerName) {
      if (!partnerId) {
        layer.msg("用户获取失败,请刷新页面再进行设置!", {
          time: 1000,
        });
        return;
      }
      //获取选中的树节点
      this.bindPremisesInfo.partnerId = partnerId;
      this.bindPremisesInfo.partnerName = partnerName;
      // 打开驻守案场弹窗, 清空已选值
      this.selectPremises = [];
      $("#premisesListModal").modal({
        backdrop: "static",
        keyboard: false,
      });
    },
    openBindDeptPermissionModal(partnerId, partnerName) {
      //获取选中的树节点
      this.bindPartnerInfo.partnerId = partnerId;
      this.bindPartnerInfo.partnerName = partnerName;
      // 打开驻守案场弹窗, 清空已选值
      this.selectPremises = [];
      $("#selfDeptPermissionModal").modal({
        backdrop: "static",
        keyboard: false,
      });
    },
    // 消息配置
    openMessageSettingModal(partnerId, partnerName) {
      //获取选中的树节点
      this.bindPremisesInfo.partnerId = partnerId;
      this.bindPremisesInfo.partnerName = partnerName;
      // 打开消息配置弹窗, 清空已选值
      this.selectPremises = [];
      this.messageModalShow = true;
      $("#messageSettingModal").modal({
        backdrop: "static",
        keyboard: false,
      });
    },
    bindPremisesReturn() {
      this.loadPartnerByDept(true);
    },
    openEditDeptModal(optType) {
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length == 0) {
        layer.msg("请选择一个部门 ", {
          time: 1000,
        });
        return;
      }
      if (nodes[0].level == 0) {
        layer.msg("顶级部门不能修改");
        return;
      }
      if ("M" == optType) {
        this.acceptDept.id = nodes[0].id;
        this.acceptDept.name = nodes[0].name;
        this.acceptDept.level = nodes[0].level;
        this.$refs.mergeD.loadOrgTreeData();
        $("#mergeDeptModal").modal("show");
      } else if ("C" == optType) {
        this.acceptDept.id = nodes[0].id;
        this.acceptDept.name = nodes[0].name;
        this.acceptDept.level = nodes[0].level;
        this.$refs.changeD.loadOrgTreeData();
        $("#changeDeptModal").modal("show");
      }
    },
    openChangePartnerDept: function(id, name) {
      var setting = {
        data: {
          simpleData: {
            enable: true,
          },
        },
      };
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      this.partnerInfo.id = id;
      this.partnerInfo.name = name;
      if (treeObj) {
        $.fn.zTree.init($("#partnerTree"), setting, treeObj.getNodes());
      }
      $("#changePartnerDeptModal").modal("show");
    },
    queryDetpByDeptName: function() {
      var _self = this;
      var node_type = "name";
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNode = treeObj.transformToArray(treeObj.getNodes());
      treeObj.hideNodes(allNode);

      var keywords = _self.searchDeptModel.deptName;
      if (keywords == "") {
        $("#orgTreeText").hide();
        treeObj.showNodes(allNode);
        treeObj.expandAll(false);
      } else {
        //_self.nodeList = treeObj.getNodesByParamFuzzy("text", keywords, null);
        _self.nodeList = treeObj.getNodesByFilter(_self.filterFunc);
        _self.nodeList = treeObj.transformToArray(_self.nodeList);
        for (var n in _self.nodeList) {
          if (_self.nodeList.hasOwnProperty(n)) {
            _self.findParent(treeObj, _self.nodeList[n]);
          }
        }
        if (_self.nodeList.length > 0) {
          $("#orgTreeText").hide();
          treeObj.showNodes(_self.nodeList);
        } else {
          $("#orgTreeText").show();
        }
      }
    },
    filterFunc: function(node) {
      var _self = this;
      var keywords = _self.searchDeptModel.deptName;
      if (node.name.indexOf(keywords) != -1) return true;
      return false;
    },
    findParent: function(treeObj, node) {
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      treeObj.expandNode(node, true, false, false);
      var pNode = node.getParentNode();
      if (pNode != null) {
        _self.nodeList.push(pNode);
        _self.findParent(treeObj, pNode);
      }
    },
    getQRCodeInfoByNode(node) {
      if (node.level == 0) {
        this.qrcodeNode.orgName = node.name;
        this.qrcodeNode.orgId = node.merchantId;
        this.qrcodeNode.storeName = "";
        this.qrcodeNode.storeId = "";
        this.qrcodeNode.groupName = "";
        this.qrcodeNode.groupId = "";
      }
      if (node.level == 1) {
        this.qrcodeNode.storeName = node.name;
        this.qrcodeNode.storeId = node.id;
        let pnode = node.getParentNode();
        if (pnode) {
          this.qrcodeNode.orgName = pnode.name;
          this.qrcodeNode.orgId = pnode.merchantId;
        }
        this.qrcodeNode.groupName = "";
        this.qrcodeNode.groupId = "";
      }
      if (node.level == 2) {
        this.qrcodeNode.groupName = node.name;
        this.qrcodeNode.groupId = node.id;
        let snode = node.getParentNode();
        if (snode) {
          this.qrcodeNode.storeName = snode.name;
          this.qrcodeNode.storeId = snode.id;
          let pnode = snode.getParentNode();
          if (pnode) {
            this.qrcodeNode.orgName = pnode.name;
            this.qrcodeNode.orgId = pnode.merchantId;
          }
        }
      }
    },
  },
};
</script>